//version1.1.1, 修改了对旧数据的兼容,允许只赋值市或者区
layui.define(['form','layer'], function(ex) {
	var $ = layui.$,
		layer = layui.layer,
		form = layui.form;
	var _provinces = ["北京市", "天津市", "上海市", "重庆市", "河北省", "河南省", "湖北省", "湖南省", "江苏省", "江西省", "辽宁省", "吉林省", "黑龙江",
		"陕西省", "山西省", "山东省", "四川省", "青海省", "安徽省", "海南省", "广东省", "贵州省", "浙江省", "福建省", "甘肃省", "云南省", "西藏自治区",
		"宁夏回族自治区", "广西壮族自治区", "新疆维吾尔自治区", "内蒙古自治区", "香港特别行政区", "澳门特别行政区", "台湾省"
	]
	var _pcatype = {
		province: "province", city: "city", area: "area"
	}
	var _placeholderMap = {
		"province" : "请选择省",
		"city" : "请选择市",
		"area" : "请选择区/县"
	}
	function reqAmapCityDistDatas(akey, prov) {
		var pcaIns = this;
		if(!akey){
			layer.alert("请传入你的高德key")
			console.error("请传入你的高德key")
			return
		}
		if(!prov){
			layer.alert("请传入选择的省份")
			console.error("请传入选择的省份")
			return
		}
		$.ajax({
			url: '//restapi.amap.com/v3/config/district?key=' + akey + '&keywords=' + prov +
				'&subdistrict=2&output=JSON',
			async: false,
			success: function(res){
				pcaIns.pcadatas = res.districts[0] || {}
			}
		})
	}

	function renderLayuiSelect($selElem, type, amapDatas){
		var formfilter = $selElem.parent().attr("lay-filter") || ("Lay-form-"+type + '-' + this._id)
		//render元素
		$selElem.parent().addClass("layui-form")
		$selElem.parent().attr("lay-filter", formfilter)
		
		$selElem.attr("lay-filter", $selElem.attr("lay-filter") || "Lay-form-pca-select-" + this._id)
		$selElem.html('<option value="">' + _placeholderMap[type] + '</option>')
		//填充数据
		if(type==_pcatype.province){
			$(_provinces).each(function() {
				$selElem.append('<option>' + this + '</option>')
			})
		}
		else if(amapDatas){
			amapDatas.sort((a, b) => {
				return a.adcode - b.adcode;
			})
			$(amapDatas).each(function() {
				$selElem.append('<option>' + this.name + '</option>')
			})
		}
		
		//渲染
		form.render(null, formfilter)
	}

	function layuiRender(cities, areas) {
		var {$province, $city, $area} = this
		$province.attr("name") ? null : layer.alert("请为'#" + $province.attr("id") + "'元素配置name属性, 否则无法赋值")
		$city.attr("name") ? null : layer.alert("请为'#" + $city.attr("id") + "'元素配置name属性, 否则无法赋值")
		$area.attr("name") ? null : layer.alert("请为'#" + $area.attr("id") + "'元素配置name属性, 否则无法赋值")

		renderLayuiSelect.call(this, $province, _pcatype.province)
		renderLayuiSelect.call(this, $city, _pcatype.city)
		renderLayuiSelect.call(this, $area, _pcatype.area)
	}
	function setVal(pval, cval, aval) {
		if(!this.pcadatas.districts && pval){
			reqAmapCityDistDatas.call(this, this.amapkey, pval)
		}
		if (pval) {
			var pValData = {}
			pValData[this.$province.attr('name')] = pval
			form.val(this.$province.parent().attr("lay-filter"), pValData)
			renderLayuiSelect.call(this, this.$city, _pcatype.city, this.pcadatas.districts)
		}
		else{//如果省为空,市不为空
			if(cval){
				this.pcadatas.districts = [{adcode:0,name:cval}]
				renderLayuiSelect.call(this, this.$city, _pcatype.city, this.pcadatas.districts)
			}
		}
		if (cval) {
			var cValData = {}
			cValData[this.$city.attr('name')] = cval
			form.val(this.$city.parent().attr("lay-filter"), cValData)

			var cities = this.pcadatas.districts || []
			var areas;
			$(cities).each(function() {
				if (this.name === cval) {
					areas = this.districts
					return false;
				}
			})
			if(!areas && aval){
				areas = [{adcode:0,name:aval}]
			}
			renderLayuiSelect.call(this, this.$area, _pcatype.area, areas)
		}
		else if(aval){
			renderLayuiSelect.call(this, this.$area, _pcatype.area, [{adcode:0,name:aval}])
		}
		if (aval) {
			var aValData = {}
			aValData[this.$area.attr('name')] = aval
			form.val(this.$area.parent().attr("lay-filter"), aValData)
		}
	}

	ex("pca", {
		initPca: function(amapkey, $pselect, $cselect, $aselect, pval, cval, aval) {
			var pcaInstance = {
				"amapkey" : amapkey,
				"$province": $pselect,
				"$city": $cselect,
				"$area": $aselect,
				"pcadatas": {},
				"_id" : new Date().getTime()
			}
			layuiRender.call(pcaInstance, $pselect, $cselect, $aselect)
			setVal.call(pcaInstance, pval, cval, aval)
			
			form.on('select(Lay-form-pca-select-'+pcaInstance._id+')', function(data) {
				console.log('选择', data.value); //得到被选中的值
				var pcatype = $(data.elem).data('type')
				if(pcatype == _pcatype.province){
					data.value && reqAmapCityDistDatas.call(pcaInstance, pcaInstance.amapkey, data.value)
					renderLayuiSelect.call(pcaInstance, $cselect, _pcatype.city, pcaInstance.pcadatas.districts)
					renderLayuiSelect.call(pcaInstance, $aselect, _pcatype.area)
				}
				else if(pcatype == _pcatype.city){
					var cities = pcaInstance.pcadatas.districts
					var cityDistricts;
					$(cities).each(function() {
						if (this.name === data.value) {
							cityDistricts = this.districts
							return false;
						}
					})
					cityDistricts.sort((a, b) => {
						return a.adcode - b.adcode;
					})
					renderLayuiSelect.call(pcaInstance, $aselect, _pcatype.area, cityDistricts)
				}
				else{
					console.log('选择区县暂时不处理事件')
				}
			})
		}
	})
});

